#! /usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys
import shutil
import time
import codecs
import argparse
import shutil

# how to use
# ./python_version_change -main_git_ver "develop" -module_match_list "ModuleMatchingVersion.txt"

reload(sys)

sys.setdefaultencoding("utf-8")

global workSpacePath
workSpacePath=os.getcwd() + '/'

class ModuleInfo(object):
    path = ''
    version = ''

    def __init__(self,path,version):
        self.path = path
        self.version = version

class RebuildBase(object):
    def __init__(self):
        pass

    def runTask(self, curPath):
        pass


class RebuildHeaderTool(RebuildBase):


    def changeGitVersion(self, modulePath,girVersion):

        word_dir = "cd %s &&" % modulePath
        if modulePath.find('MainProject') != -1:
            word_dir = 'ls &&'
            return
            # word_dir = "cd %s &&" % workSpacePath




        cmd = "git branch"
        
        cmd1 = "%s git checkout ."  % (word_dir)
        p = os.popen(cmd1)
        print(p.read())

        cmd2 = "%s git checkout -b %s --track origin %s" % (word_dir,girVersion,girVersion)
        p = os.popen(cmd2)
        print(p.read())


        cmd3 = "%s git checkout %s" % (word_dir,girVersion)
        p = os.popen(cmd3)
        print(p.read())

        cmd4 = "%s git pull" % (word_dir)
        p = os.popen(cmd4)
        print(p.read())

    def parsingFile(self,filePath):
        moduleNameList = []
        moduleLines = []
        moduleList = []

        file_object = open(filePath, "r+")
        tmplines = file_object.readlines()
        file_object.close()

        lines = []
        for line in tmplines:
            line = line.replace(" ","").replace("\n","")
            if line.find(';') == 0 or len(line) == 0:
                continue;
            lines.append(line)


        for line in lines:
            if line.find(';') == 0 or len(line) == 0:
                continue
            if line.find('ModuleFolder') != -1:
                line = line.split('=')[1]
                moduleNameList = line.split(',')

        record = 0
        tmpLines = []
        for line in lines:
            if line.find('MainProject') != -1 or line.find('//end') != -1:
                if record == 1:
                    moduleLines.append(tmpLines)
                    tmpLines = []
                    tmpLines.append(line)
                else:
                    record = 1
                    tmpLines.append(line)
            elif record == 1:
                tmpLines.append(line)
                pass

        for lines in moduleLines:
            tmp = []
            for line in lines:
                key = line.split('=')[0]
                val = line.split('=')[1]
                tmp.append(ModuleInfo(key,val))
            moduleList.append(tmp)

        return moduleList


# ----------------------------------------------------main------------------------------------------------
def parse_args():
    global script_path, proj_ios_path
    parser = argparse.ArgumentParser(description='模块批量切换分支.\n')
    parser.add_argument('-main_git_ver', dest='main_git_ver', type=str, required=False, default="",
                        help='主工程分支名,匹配版本文件必须含有主工程匹配版本的描述')
    parser.add_argument('-module_match_list', dest='module_match_list', type=str, required=False, default="ModuleMatchingVersion.txt",
                        help='主项目相对于工程路径')
    args = parser.parse_args()
    return args


def main():
    startTime = time.time()




    app_args = parse_args()
    main_git_ver = app_args.main_git_ver
    module_match_list = app_args.module_match_list

    tool = RebuildHeaderTool()
    list = tool.parsingFile(workSpacePath + module_match_list)
    isHasChangeVersion = 0
    for singleList in list:
        for tmp in singleList:
            if tmp.path == 'MainProject' and tmp.version == main_git_ver:
                isHasChangeVersion = 1
                tool.changeGitVersion(workSpacePath + tmp.path, tmp.version)
            elif isHasChangeVersion == 1:
                tool.changeGitVersion(workSpacePath+tmp.path,tmp.version)

    if isHasChangeVersion == 1:
        print("处理成功")
    else:
        print("没有找到对应版本")
    endTime = time.time()
    print("总耗时: %0.2f" % (endTime - startTime))


if __name__ == "__main__":
    main()
